package com.cp.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cp.common.exception.Assert;
import com.cp.common.result.ResponseEnum;
import com.cp.core.enums.BorrowAuthEnum;
import com.cp.core.enums.BorrowInfoStatusEnum;
import com.cp.core.enums.BorrowerStatusEnum;
import com.cp.core.mapper.BorrowInfoMapper;
import com.cp.core.pojo.entity.BorrowInfo;
import com.cp.core.pojo.entity.Borrower;
import com.cp.core.pojo.entity.IntegralGrade;
import com.cp.core.pojo.entity.UserInfo;
import com.cp.core.pojo.vo.BorrowInfoApprovalVO;
import com.cp.core.pojo.vo.BorrowerDetailVO;
import com.cp.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.cp.core.enums.UserBindEnum;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author ming
 * @since 2022-07-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private IntegralGradeService integralGradeService;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerService borrowerService;
    @Resource
    private LendService lendService;
    @Override
    public BigDecimal getAmountByUserId(Long userId) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>().eq("id", userId);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        Assert.isTrue(userInfo!=null, ResponseEnum.LOGIN_MOBILE_ERROR);
        QueryWrapper<IntegralGrade> gradeQueryWrapper = new QueryWrapper<>();
        Integer integral = userInfo.getIntegral();
        gradeQueryWrapper.le("integral_start",integral).ge("integral_end",integral);
        IntegralGrade integralGrade = integralGradeService.getOne(gradeQueryWrapper);
        if(integralGrade == null) return new BigDecimal("0");
        return integralGrade.getBorrowAmount();
    }

    @Override
    public void saveBorrowerInfo(BorrowInfo borrowInfo, Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        //判断用户绑定状态
        Assert.isTrue(userInfo.getBindStatus().intValue()==UserBindEnum.BIND_OK.getStatus().intValue(),ResponseEnum.USER_NO_BIND_ERROR);

       // 判断额度审批状态
        Assert.isTrue(userInfo.getBorrowAuthStatus().intValue()== BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),ResponseEnum.USER_NO_AMOUNT_ERROR);
      //判断借款人额度是佛充足
        Assert.isTrue(this.getAmountByUserId(userId).compareTo(borrowInfo.getAmount())>=0,ResponseEnum.USER_AMOUNT_LESS_ERROR);
        borrowInfo.setUserId(userId);
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal("100")));
        //设置审核状态
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        this.baseMapper.insert(borrowInfo);

    }

    @Override
    public Integer getBorrowerInfoStatusByUserId(Long userId) {
        List<Object> objects = this.baseMapper.selectObjs(new QueryWrapper<BorrowInfo>().eq("user_id", userId).select("status"));
        if(objects.size()==0) return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        return (Integer)objects.get(0);
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList = this.baseMapper.selectBorrowInfoList();
        for (BorrowInfo borrowInfo : borrowInfoList) {
            String returnMethod = dictService.getNameByDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = dictService.getNameByDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            borrowInfo.getParam().put("returnMethod",returnMethod);
            borrowInfo.getParam().put("moneyUse",moneyUse);
            borrowInfo.getParam().put("status",status);
        }
        return borrowInfoList;

    }

    @Override
    public Map<String, Object> getBorrowerInfoDetail(Long id) {
        //借款对象BorrowInfo
        BorrowInfo borrowInfo = this.getById(id);
        String returnMethod = dictService.getNameByDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod",returnMethod);
        borrowInfo.getParam().put("moneyUse",moneyUse);
        borrowInfo.getParam().put("status",status);
        Borrower borrower = borrowerService.getOne(new QueryWrapper<Borrower>().eq("user_id", borrowInfo.getUserId()));
        BorrowerDetailVO borrowerDetail = borrowerService.getBorrowerDetailVoById(borrower.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("borrowInfo",borrowInfo);
        map.put("borrower",borrowerDetail);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        //1.修改借款审核状态
        BorrowInfo borrowInfo = this.baseMapper.selectById(borrowInfoApprovalVO.getId());
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);
        //2.产生新的标的记录 lend
        if(borrowInfoApprovalVO.getStatus().intValue()==BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
           lendService.createLend(borrowInfoApprovalVO,borrowInfo);
        }
    }
}
